package com.jkdz.spyke.flexUI.helpers {
	import mx.core.UIComponent;

	import flash.external.ExternalInterface;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	
	public class MouseWheelManager {
		
		private static var eventTargets:Dictionary;
		
		public static function initDropping():void {
			eventTargets = new Dictionary();
			
			ExternalInterface.addCallback("mouseWheel", function(atX:int, atY:int, delta:int):void {
				var tti:UIComponent = null;
				for (var i:* in eventTargets) {
					var ti:UIComponent = i;
					if (ti.hitTestPoint(atX, atY)) {
						if (tti == null) {
							tti = ti;
						} else {
							if (isHigherThan(ti, tti)) {
								tti = ti;
							}
						}
					}
				}
				var f:Function = eventTargets[tti];
				if (f != null) {
					var p:Point = tti.globalToContent(new Point(atX, atY));
					f(p.x, p.y, delta);
				}
			});

		}

		private static function isHigherThan(a:UIComponent, b:UIComponent):Boolean {
			var aps:Vector.<UIComponent> = getOwners(a);
			var bps:Vector.<UIComponent> = getOwners(b);
			
			var tap:UIComponent = a;
			for each (var ap:UIComponent in aps) {
				var tbp:UIComponent = b;
				for each (var bp:UIComponent in bps) {
					if (ap == bp) {
						return isHigherInSameContainerThan(tap, tbp);
					}
					tbp = bp;
				}
				tap = ap;
			}
			
			return false;
		}
		
		private static function isHigherInSameContainerThan(a:UIComponent, b:UIComponent):Boolean {
			if (a.depth == b.depth) {
				return a.parent.getChildIndex(a) > b.parent.getChildIndex(b);
			} else {
				return a.depth > b.depth;
			}
		}
		
		private static function getOwners(e:UIComponent):Vector.<UIComponent> {
			var ret:Vector.<UIComponent> = new Vector.<UIComponent>();
			while (e.owner != null && e.owner is UIComponent && e.owner != e) {
				e = (UIComponent)(e.owner);
				ret.push(e);
			}
			ret.push(null);
			return ret;
		}
		
		public static function addMouseWheelListener(element:UIComponent, listener:Function):void {
			eventTargets[element] = listener;
		}
		
		public static function removeMouseWheelListener(element:UIComponent):void {
			delete eventTargets[element];
		}
	}
}